package com.team9.fitness.service;

import com.team9.fitness.entity.DietRecord;
import com.team9.fitness.entity.FoodInfo;
import com.team9.fitness.mapper.DietRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

/**
 * 饮食记录服务
 */
@Service
@Transactional
@Slf4j
public class DietRecordService {

    @Autowired
    private DietRecordMapper dietRecordMapper;

    @Autowired
    private FoodInfoService foodInfoService;

    /**
     * 创建饮食记录
     */
    public DietRecord createDietRecord(DietRecord dietRecord) {
        // 获取食物信息并计算营养成分
        FoodInfo foodInfo = foodInfoService.getFoodInfoById(dietRecord.getFoodId());
        if (foodInfo == null) {
            throw new RuntimeException("食物信息不存在");
        }

        // 计算营养成分（按比例计算）
        double ratio = dietRecord.getAmount() / 100.0;
        dietRecord.setTotalCalories(foodInfo.getCalories() * ratio);
        dietRecord.setTotalCarbohydrates(foodInfo.getCarbohydrates() * ratio);
        dietRecord.setTotalProtein(foodInfo.getProtein() * ratio);
        dietRecord.setTotalFat(foodInfo.getFat() * ratio);

        dietRecord.setCreatedAtIfNull();
        dietRecordMapper.insert(dietRecord);

        return dietRecord;
    }

    /**
     * 根据ID获取饮食记录
     */
    public DietRecord getDietRecordById(Long id) {
        return dietRecordMapper.selectById(id);
    }

    /**
     * 获取用户的所有饮食记录
     */
    public List<DietRecord> getDietRecordsByUserId(Long userId) {
        return dietRecordMapper.selectByUserId(userId);
    }

    /**
     * 获取用户指定日期的饮食记录
     */
    public List<DietRecord> getDietRecordsByUserIdAndDate(Long userId, LocalDateTime date) {
        return dietRecordMapper.selectByUserIdAndDate(userId, date);
    }

    /**
     * 获取用户指定日期和餐次的饮食记录
     */
    public List<DietRecord> getDietRecordsByUserIdAndMealTypeAndDate(Long userId, String mealType, LocalDateTime date) {
        return dietRecordMapper.selectByUserIdAndMealTypeAndDate(userId, mealType, date);
    }

    /**
     * 获取用户指定日期的营养汇总
     */
    public DietRecord getDailyNutritionSummary(Long userId, LocalDateTime date) {
        return dietRecordMapper.getDailyNutritionSummary(userId, date);
    }

    /**
     * 更新饮食记录
     */
    public DietRecord updateDietRecord(DietRecord dietRecord) {
        // 重新计算营养成分
        FoodInfo foodInfo = foodInfoService.getFoodInfoById(dietRecord.getFoodId());
        if (foodInfo == null) {
            throw new RuntimeException("食物信息不存在");
        }

        double ratio = dietRecord.getAmount() / 100.0;
        dietRecord.setTotalCalories(foodInfo.getCalories() * ratio);
        dietRecord.setTotalCarbohydrates(foodInfo.getCarbohydrates() * ratio);
        dietRecord.setTotalProtein(foodInfo.getProtein() * ratio);
        dietRecord.setTotalFat(foodInfo.getFat() * ratio);

        dietRecordMapper.update(dietRecord);
        return dietRecord;
    }

    /**
     * 删除饮食记录
     */
    public void deleteDietRecord(Long id) {
        dietRecordMapper.deleteById(id);
    }

    /**
     * 删除用户指定日期的所有饮食记录
     */
    public void deleteDietRecordsByUserIdAndDate(Long userId, LocalDateTime date) {
        dietRecordMapper.deleteByUserIdAndDate(userId, date);
    }

    /**
     * 创建饮食记录业务逻辑（供ZRDDS调用）
     */
    public DietRecord createDietRecordByZRDDS(Long userId, Long foodId, Double amount, String mealType) {
        try {
            // 获取食物信息并计算营养成分
            FoodInfo foodInfo = foodInfoService.getFoodInfoById(foodId);
            if (foodInfo == null) {
                log.warn("食物信息不存在: foodId={}", foodId);
                return null;
            }

            // 创建饮食记录
            DietRecord dietRecord = new DietRecord();
            dietRecord.setUserId(userId);
            dietRecord.setFoodId(foodId);
            dietRecord.setAmount(amount);
            dietRecord.setMealType(mealType);

            // 计算营养成分（按比例计算）
            double ratio = amount / 100.0;
            dietRecord.setTotalCalories(foodInfo.getCalories() * ratio);
            dietRecord.setTotalCarbohydrates(foodInfo.getCarbohydrates() * ratio);
            dietRecord.setTotalProtein(foodInfo.getProtein() * ratio);
            dietRecord.setTotalFat(foodInfo.getFat() * ratio);

            dietRecord.setCreatedAtIfNull();
            dietRecordMapper.insert(dietRecord);

            log.info("创建饮食记录成功: recordId={}, userId={}, foodId={}", dietRecord.getId(), userId, foodId);
            return dietRecord;
        } catch (Exception e) {
            log.error("创建饮食记录失败: userId={}, foodId={}", userId, foodId, e);
            return null;
        }
    }

    /**
     * 获取每日营养汇总业务逻辑（供ZRDDS调用）
     */
    public DietRecord getDailyNutritionSummaryByZRDDS(Long userId, String dateStr) {
        try {
            LocalDateTime date = LocalDateTime.parse(dateStr);
            DietRecord summary = dietRecordMapper.getDailyNutritionSummary(userId, date);
            log.info("获取营养汇总成功: userId={}, date={}", userId, dateStr);
            return summary;
        } catch (Exception e) {
            log.error("获取营养汇总失败: userId={}, date={}", userId, dateStr, e);
            return null;
        }
    }
}
